package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.vo.*;
import com.jsh.erp.service.accountHead.AccountHeadService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.Constants;
import com.jsh.erp.utils.ErpInfo;
import com.jsh.erp.utils.StringUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 * @author jishenghua 752*718*920
 */
@RestController
@RequestMapping(value = "/accountHead")
@Api(tags = {"财务管理"})
public class AccountHeadController {
    private Logger logger = LoggerFactory.getLogger(AccountHeadController.class);

    @Resource
    private AccountHeadService accountHeadService;
    @Resource
    private RedisService redisService;
    /**
     * 批量设置状态-审核或者反审核
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping(value = "/batchSetStatus")
    @ApiOperation(value = "批量设置状态-审核或者反审核")
    public String batchSetStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request) throws Exception{
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String status = jsonObject.getString("status");
        String ids = jsonObject.getString("ids");
        int res = accountHeadService.batchSetStatus(status, ids);
        if(res > 0) {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.ERROR.name : ErpInfo.ERROR.lanCodeName, ErpInfo.ERROR.code);
        }
    }

    /**
     * 新增财务主表及财务子表信息
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addAccountHeadAndDetail")
    @ApiOperation(value = "新增财务主表及财务子表信息")
    public Object addAccountHeadAndDetail(@RequestBody AccountHeadVo4Body body, HttpServletRequest request) throws  Exception{
         String lanCode = redisService.getLanCodeFromSession(request);
        JSONObject result = ExceptionConstants.standardSuccess(lanCode);
        String beanJson = body.getInfo();
        String rows = body.getRows();
        String attachment = body.getAttachment();
        Boolean passDirect = body.getPassDirect();
        String functionId = body.getFunctionId();
        accountHeadService.addAccountHeadAndDetail(beanJson,rows,attachment, request,passDirect,functionId);
        return result;
    }

    /**
     * 更新财务主表及财务子表信息
     * @param body
     * @param request
     * @return
     * @throws Exception
     */
    @PutMapping(value = "/updateAccountHeadAndDetail")
    @ApiOperation(value = "更新财务主表及财务子表信息")
    public Object updateAccountHeadAndDetail(@RequestBody AccountHeadVo4Body body, HttpServletRequest request) throws Exception{
         String lanCode = redisService.getLanCodeFromSession(request);
        JSONObject result = ExceptionConstants.standardSuccess(lanCode);
        String beanJson = body.getInfo();
        String rows = body.getRows();
        String attachment = body.getAttachment();
        Boolean passDirect = body.getPassDirect();
        String functionId = body.getFunctionId();
        accountHeadService.updateAccountHeadAndDetail(beanJson,rows,attachment,request,passDirect,functionId);
        return result;
    }

    /**
     * 根据编号查询单据信息
     * @param billNo
     * @param request
     * @return
     */
    @GetMapping(value = "/getDetailByNumber")
    @ApiOperation(value = "根据编号查询单据信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountHeadVo4ListEx.class)
    })
    public BaseResponseInfo getDetailByNumber(@RequestParam("billNo") String billNo,
                                              HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        AccountHeadVo4ListEx ahl = new AccountHeadVo4ListEx();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<AccountHeadVo4ListEx> list = accountHeadService.getDetailByNumber(billNo);
            if(list.size() == 1) {
                ahl = list.get(0);
            }
            res.code = 200;
            res.data = ahl;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }

    /**
     * 根据出入库单据id查询收付款单号
     * @param billId
     * @param request
     * @return
     */
    @GetMapping(value = "/getFinancialBillNoByBillId")
    @ApiOperation(value = "根据编号查询单据信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountHead.class)
    })
    public BaseResponseInfo getFinancialBillNoByBillId(@RequestParam("billId") String billId,
                                              HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<AccountHead> list = accountHeadService.getFinancialBillNoByBillId(billId);
            res.code = 200;
            res.data = list;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }
//
//    @GetMapping(value = "/getAccountHeadByOrganId")
//    @ApiOperation(value = "根据客户/供应商ID查询财务信息")
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "ok", response = AccountHead.class)
//    })
//    public String getAccountHeadByOrganId(@RequestParam(value = Constants.SEARCH, required = false) String search,
//                                                    @RequestParam("currentPage") Integer currentPage,
//                                                    @RequestParam("pageSize") Integer pageSize,
//                                                       HttpServletRequest request)throws Exception {
//        Map<String, Object> objectMap = new HashMap<>();
//        String lanCode = redisService.getLanCodeFromSession(request);
//        String organId = StringUtil.getInfo(search, "organId");
//        String beginTime = StringUtil.getInfo(search, "beginTime");
//        String endTime = StringUtil.getInfo(search, "endTime");
//        String number = StringUtil.getInfo(search, "number");
//        List<AccountHeadVo> list = accountHeadService.getListByOrganId(organId,beginTime,endTime,number,(currentPage - 1) * pageSize, pageSize);
//        if (list != null) {
//            objectMap.put("rows", list);
//            objectMap.put("total", accountHeadService.getListByOrganId(organId,beginTime,endTime,number,null, null).size());
//            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
//        } else {
//            objectMap.put("rows", new ArrayList<>());
//            objectMap.put("total",0);
//            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
//        }
//    }

    @GetMapping(value = "/getAccountHeadByOrganId")
    @ApiOperation(value = "根据客户/供应商ID查询所有信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountHeadVo.class)
    })
    public String getAccountHeadByOrganId(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                          @RequestParam("currentPage") Integer currentPage,
                                          @RequestParam("pageSize") Integer pageSize,
                                          HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String organId = StringUtil.getInfo(search, "organId");
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String number = StringUtil.getInfo(search, "number");
        List<AccountHeadVo> dataList = accountHeadService.getAllBillByOrganId(organId,beginTime,endTime,number,(currentPage - 1) * pageSize, pageSize);
        int total = accountHeadService.getAllBillByOrganIdCount(organId, beginTime, endTime,number);
        objectMap.put("total", total);
        if (null !=dataList) {
            for (AccountHeadVo aEx : dataList) {
                String type = aEx.getType().replace("其它", "");
                aEx.setType(type);
                aEx.setOrganId(organId);
            }
            objectMap.put("rows", dataList);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/checkAlert")
    @ApiOperation(value = "要货申请预警")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = CheckVo.class)
    })
    public BaseResponseInfo purchaseApplicationAlert(@RequestParam(defaultValue = "1", required = false) @ApiParam("页码") Integer pageNum,
                                                     @RequestParam(defaultValue = "10", required = false) @ApiParam("显示条数") Integer pageSize,
                                                     HttpServletRequest request) throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        List<CheckVo> vo = accountHeadService.checkAlert((pageNum - 1) * pageSize, pageSize);
        Integer total = accountHeadService.checkAlert(null, null).size();
        map.put("rows", vo);
        map.put("total", total);
        res.data = map;
        res.code = 200;
        return res;
    }

    @GetMapping(value = "/freight")
    @ApiOperation(value = "运费单报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountHeadWithTransportReport.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间 (参数都在search里面) ", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "organId", value = "供应商id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "accountId", value = "结算账户id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "status", value = "是否已付款 0-未付 1-已付 2-全部", dataType = "String", dataTypeClass = String.class),
    })
    public String freight(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                    @RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String organId = StringUtil.getInfo(search, "organId");
        String accountId = StringUtil.getInfo(search, "accountId");
        String status = StringUtil.getInfo(search, "status");
        String lanCode = redisService.getLanCodeFromSession(request);
        List<AccountHeadWithTransportReport> dataList = accountHeadService.getAllBillByType(organId,beginTime,endTime,accountId,(currentPage - 1) * pageSize, pageSize,status);
        int total = accountHeadService.getAllBillByTypeCount(organId, beginTime, endTime,accountId,status);
        objectMap.put("total", total);
        if (null !=dataList) {
            objectMap.put("rows", dataList);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/invoice")
    @ApiOperation(value = "支票核销报表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountHeadWithInvoice.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间 (参数都在search里面) ", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "organId", value = "供应商id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "accountId", value = "结算账户id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "billStatus", value = "状态", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "status", value = "是否已付款 0-未付 1-已付 2-全部", dataType = "String", dataTypeClass = String.class),
    })
    public String invoice(@RequestParam(value = Constants.SEARCH, required = false) String search,
                                    @RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    HttpServletRequest request) throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String beginTime = StringUtil.getInfo(search, "beginTime");
        String endTime = StringUtil.getInfo(search, "endTime");
        String organId = StringUtil.getInfo(search, "organId");
        String accountId = StringUtil.getInfo(search, "accountId");
        String status = StringUtil.getInfo(search, "status");
        String billStatus = StringUtil.getInfo(search, "billStatus");
        String lanCode = redisService.getLanCodeFromSession(request);
        List<AccountHeadWithInvoice> dataList = accountHeadService.getInvoiceAmountByType(organId,beginTime,endTime,accountId,(currentPage - 1) * pageSize, pageSize,status,billStatus);
        int total = accountHeadService.getInvoiceAmountByTypeCount(organId, beginTime, endTime,accountId,status,billStatus);
        objectMap.put("total", total);
        if (null !=dataList) {
            objectMap.put("rows", dataList);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("rows", new ArrayList<>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/getDetailByTransportNo")
    @ApiOperation(value = "根据运输公司id查询运费单信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AccountItemWithTransport.class)
    })
    public BaseResponseInfo getDetailByTransportNo(@RequestParam(value = "custom3", required = true)@ApiParam("运输公司id") String custom3,
                                                   @RequestParam(value = "type", required = false)@ApiParam("类型 运费/直发运费") String type,
                                              HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        String lanCode = redisService.getLanCodeFromSession(request);
        try {
            List<AccountItemWithTransport> list = accountHeadService.getDetailByTransportNo(custom3,type);
            res.code = 200;
            res.data = list;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "zh".equals(lanCode) ? ErpInfo.FAILED.name : ErpInfo.FAILED.lanCodeName;
        }
        return res;
    }


    @GetMapping(value = "/getDepositByNumber")
    @ApiOperation(value = "根据厂家直发订单编号查询订金")
    public BaseResponseInfo getDepositByNumber(@RequestParam(value = "number", required = true)@ApiParam("厂家直发订单编号") String number,
                                         @RequestParam(value = "payStatus", required = true)@ApiParam("状态") String payStatus,
                                               HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        AccountHeadWithDeposit depositByNumber = accountHeadService.getDepositByNumber(number, payStatus);
        res.code = 200;
        res.data = depositByNumber;
        return res;
    }

    @GetMapping(value = "/getStatementByDaily")
    @ApiOperation(value = "获取每日对账表")
    public BaseResponseInfo getStatementByDaily(HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        List<AccountHeadWithDaily> depositByNumber = accountHeadService.getStatementByDaily();
        res.code = 200;
        res.data = depositByNumber;
        return res;
    }
}
